package cm.com.carlamanda.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;

import org.apache.log4j.Logger;

import cm.com.carlamanda.constant.CarlamandaConstant;

/**
 * 
 * 
 */
public class BasicRestUtil {
	private static Logger log = Logger.getLogger(BasicRestUtil.class);
	public static String callPostServcice(String url, String requestParam) throws Exception {
		log.info("Method callPostServcice invoke!");
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String result = "";
		log.info("call url is " + url);
		try {
			// create connection
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			log.info(conn);
			// set attribute
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("Accept-Charset", "utf-8");		
			conn.setRequestProperty("content-type", "application/json");
			conn.setDoOutput(true);
			conn.setDoInput(true);			
			// write buff
			log.info("get requestParam!" );
			out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
			log.info("get OutputStreamWriter!");
			/******
			 * 因为bpm那边获取数据时乱码，并且在接收的时候不好接收，因此采用这种方式实现不乱码的
			 * 
			 * */
			log.info("encode requestParam!");
			out.write(requestParam);
			log.info("wirte stream!");
			out.flush();
			log.info("flush stream!");
			in = new BufferedReader(
				 new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {	
			e.printStackTrace();
			log.error(e);		
			throw new Exception(e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}				
			} catch (IOException ex) {
				ex.printStackTrace();
				log.error(ex);
				throw new Exception(ex);
			}
			
		}
		log.info("result" + result);
		return result;
	}
	
	public static String getPropertiesValue(String key) {
		return getPropertiesValue(CarlamandaConstant.BPM_SERVICE_PROPERTIES,key);
	}
	
	public static String getPropertiesValue(String propertiesName, String key) {
		Properties properties = PropertyUtil.getProperties(propertiesName);
		return properties.getProperty(key);
	}
}
